import { ref, onBeforeUnmount, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import { fullScreen } from '@/utils'
import MouseEventHandler from '@/utils/mouseEventHandler'

// 鼠标事件处理
export function useMouseEvents({ handleEvent, sessionStitchMode }) {
  const videoElementRef = ref(null)
  let mouseHandler = null

  // 计算属性：根据当前视角模式计算拖拽阈值
  const ratioThreshold = computed(() => {
    return sessionStitchMode.value === 'freeview' ? 7 : 0.8
  })

  // 提取重复的自由视角模式判断
  const isFreeviewMode = () => sessionStitchMode.value === 'freeview'

  // 简化 handleDragEvent
  const handleDragEvent = (params) => {
    if (params.dragType !== 'x' && isFreeviewMode()) return
    const direction = params.moveDirection.includes('left') ? 'left' : 'right'
    handleEvent(isFreeviewMode() ? direction : 'move', params)
  }

  // 简化 handleWheelEvent
  const handleWheelEvent = (params) => {
    const zoomAction =
      {
        in: 'zoom_in',
        out: 'zoom_out'
      }[params.zoom] || 'wheel'
    handleEvent(isFreeviewMode() ? zoomAction : 'wheel', params)
  }

  // 统一错误处理
  const logError = (message) => console.error(message)

  // 创建鼠标事件配置
  const createMouseConfig = () => {
    return {
      ratioThreshold: ratioThreshold.value,
      aspectRatio: '16/9', // 视频宽高比
      eventHandlers: {
        // 点击事件
        click: (params) => {
          message.info('点击事件触发')
          handleEvent('left', params)
        },

        // 双击事件 - 全屏
        dblclick: () => {
          message.info('双击事件触发')
          if (videoElementRef.value) {
            fullScreen(videoElementRef.value)
          }
        },

        // 拖拽事件
        drag: handleDragEvent,

        // 滚轮事件
        wheel: handleWheelEvent
      }
    }
  }

  // 修改 bindMouseEvents
  const bindMouseEvents = (element) => {
    if (!element) {
      logError('无法绑定鼠标事件：目标元素不存在')
      return null
    }
    const config = createMouseConfig()
    const handler = new MouseEventHandler(element, config)
    element.addEventListener('contextmenu', (e) => e.preventDefault())
    return handler
  }

  // 修改 initMouseEvents
  const initMouseEvents = () => {
    if (videoElementRef.value) {
      mouseHandler = bindMouseEvents(videoElementRef.value)
    } else {
      logError('视频元素引用不可用，无法绑定鼠标事件')
    }
  }

  // 清理鼠标事件处理器
  const cleanupMouseEvents = () => {
    if (mouseHandler) {
      mouseHandler.destroy()
      mouseHandler = null
    }
  }

  // 监听视角模式变化，重新初始化鼠标事件处理器
  watch(
    () => sessionStitchMode.value,
    () => {
      cleanupMouseEvents()
      initMouseEvents()
    }
  )

  // 在组件卸载前清理资源
  onBeforeUnmount(() => {
    cleanupMouseEvents()
  })

  return {
    videoElementRef,
    initMouseEvents,
    cleanupMouseEvents
  }
}
